﻿using System.Text;

namespace GwLib.JqGridMvc.Extensions
{
    public static class StringBuilderExtensions
    {
        public static StringBuilder AppendTabs(this StringBuilder sb, int count)
        {
            for (int i = 0; i < count; i++) sb.Append('\t');
            return sb;
        }

        public static StringBuilder AppendJs(this StringBuilder sb, string s)
        {
            return (s == null) ? sb.Append("null") : sb.Append('"')
                .Append(s
                    .Replace("\t", "\\t")
                    .Replace("\r", "\\r")
                    .Replace("\n", "\\n")
                    .Replace("\"", "\\\""))
                .Append('"');
        }

        public static StringBuilder AppendJs(this StringBuilder sb, bool b)
        {
            return sb.Append(b ? "true" : "false");
        }

        public static StringBuilder AppendJs(this StringBuilder sb, bool? b)
        {
            return (b == null) ? sb.Append("null") : sb.AppendJs(b.Value);
        }

        public static StringBuilder AppendJs(this StringBuilder sb, int[] ints)
        {
            if (ints == null) return sb.Append("null");
            sb.Append("[");
            int j = 0;
            foreach (int i in ints)
            {
                if (j > 0) sb.Append(", ");
                sb.Append(i);
                j++;
            }
            return sb.Append("]");
        }

        public static StringBuilder AppendSql(this StringBuilder sb, string s)
        {
            return (s == null) ? sb.Append("null") : sb.Append('\'')
                .Append(s.Replace("'", "''"))
                .Append('\'');
        }
    }
}